<template>
	<view class="wrapping">
		<!-- header 定位后以左上角顺时针旋转 90° -->
		<view class="header-title flex col-center">
			<!-- <text> 签名：</text> -->
			<!-- 预览图片（图片本身是正向的，但由于父元素旋转了90°所以正好能横向观看） -->
			<!-- <image :src="previewImage" mode="aspectFit" class="small-preview" /> -->
			<text class="desc-text">{{ description }}</text>
		</view>
		<!-- 实际保持直立正向 canvas 容器 -->
		<view class="canvas-wrapper">
			<!-- 只展示限制数量文字的米字格，超过配置数量文字则不展示 -->
			<view class="char-group flex-col flex-center" v-if="signText && signText.length <= riceGridLimit">
				<view class="char-box" v-for="(item, index) in signText" :key="index">
					{{ item }}
				</view>
			</view>
			<canvas id="signatureCanvas" type="2d" class="signature-canvas" @touchstart="handleTouchStart"
				@touchmove="handleTouchMove" @touchend="handleTouchEnd" @touchcancel="handleTouchEnd"
				disable-scroll></canvas>
		</view>
		<!-- footer 定位后以右下角顺时针旋转 90° -->
		<view class="footer-btn flex">
			<view class="action-btn" @click="back_fun">返回</view>
			<view class="action-btn" @click="resetCanvas">重签</view>
			<view class="action-btn submit-btn" @click="handleSubmit">{{ submitText }}</view>
		</view>
		<!--用于绘制并生成旋转为正向签名图片的 canvas 容器-->
		<canvas id="previewCanvas" type="2d" class="preview-canvas"></canvas>
	</view>
</template>

<script>
	// import sites from '../../common/sites.js';
	import {
		uploadBase64
	} from '@/api/system/pcqd.js'
	import {
		getSig
	} from '@/api/system/user.js'

	export default {
		props: {
			description: {
				type: String,
				default: '请使用正楷字体，逐字签写', //  文字描述
			},
			submitText: {
				type: String,
				default: '提交', // 提交按钮文字
			},
			dotSize: {
				type: Number,
				default: 4, // 签名笔大小
			},
			penColor: {
				type: String,
				default: '#000000', // 签名笔颜色
			},
			// signText: {
			// 	type: String,
			// 	default: '', // 签名文字
			// },
			// riceGridLimit: {
			// 	type: Number,
			// 	default: 3, // 米字格展示字数最大限制
			// },
		},
		data() {
			return {
				mainCtx: null,
				mainCanvas: null,
				isDrawing: false,
				touchPoints: [],
				signIsMove: false,
				previewImage: '',
				canvasRatio: 1,
				signText: '',
				sxqm_path: '',
				u_token: '',
				params: {},
				riceGridLimit: 3
			};
		},
		mounted() {
			this.canvasRatio = uni.getWindowInfo().pixelRatio ?? 1;
			this.initCanvas();
			// let userinfo = uni.getStorageSync('user_info');
			this.signText = this.$store.state.user.nickname
			console.log('this.signText', this.signText)
		},
		methods: {
			//返回上一页
			back_fun() {
				uni.navigateBack();
			},
			initCanvas() {
				const domItem = uni.createSelectorQuery().in(this).select('#signatureCanvas');
				domItem.fields({
					node: true,
					size: true
				}).exec((res) => {
					// Canvas 对象
					this.mainCanvas = res[0]?.node;
					// 渲染上下文
					this.mainCtx = this.mainCanvas.getContext('2d');
					// Canvas 画布的实际绘制宽高
					const width = res[0].width;
					const height = res[0].height;
					// 初始化画布大小
					this.mainCanvas.width = width * this.canvasRatio;
					this.mainCanvas.height = height * this.canvasRatio;
					this.mainCtx.scale(this.canvasRatio, this.canvasRatio);
					this.setPen();
				});
			},
			setPen() {
				this.mainCtx.strokeStyle = this.penColor;
				this.mainCtx.lineWidth = this.dotSize;
				this.mainCtx.lineCap = 'round';
				this.mainCtx.lineJoin = 'round';
			},
			handleTouchStart(e) {
				const point = {
					x: e.changedTouches[0].x,
					y: e.changedTouches[0].y,
				};
				this.touchPoints.push(point);
				this.isDrawing = true;
			},
			handleTouchMove(e) {
				if (!this.isDrawing) return;
				const point = {
					x: e.touches[0].x,
					y: e.touches[0].y,
				};
				this.touchPoints.push(point);
				const len = this.touchPoints.length;
				if (len >= 2) {
					const prevPoint = this.touchPoints[len - 2];
					const currentPoint = this.touchPoints[len - 1];
					this.mainCtx.beginPath();
					this.mainCtx.moveTo(prevPoint.x, prevPoint.y);
					this.mainCtx.lineTo(currentPoint.x, currentPoint.y);
					this.mainCtx.stroke();
					this.signIsMove = true;
				}
			},
			handleTouchEnd() {
				this.isDrawing = false;
				this.touchPoints = [];
			},
			resetCanvas() {
				if (!this.signIsMove) {
					return;
				}
				this.mainCtx.clearRect(0, 0, 1000, 1000);
				this.setPen();
				this.touchPoints = [];
				this.previewImage = '';
				this.signIsMove = false;
			},
			async handleSubmit() {
				let u_token = uni.getStorageSync('Token');
				this.u_token = u_token;
				if (!this.signIsMove) {
					uni.showToast({
						title: '请先完成签名',
						icon: 'none'
					});
					return;
				}
				try {
					const _this = this;
					uni.canvasToTempFilePath({
						canvas: this.mainCanvas,
						quality: 1,
						fileType: 'png',
						success: (res) => {

							uni.getFileSystemManager().readFile({
								filePath: res.tempFilePath, //选择图片返回的相对路径
								encoding: 'base64', //编码格式
								success: res => { //成功的回调
									let base64 = 'data:image/jpeg;base64,' + res
										.data //不加上这串字符，在页面无法显示的哦
									// this.imgBase64URL=base64
									console.log('base64', base64)
									uploadBase64({
										base64,
										bizType: 'sig'
									}).then(res => {
										console.log('res', res)
										// that.InvestigationList[index].hiddenFile = res.data.id
										getSig(res.data.id).then(res => {
											console.log('res', res)
											_this.$store.dispatch('GetInfo').then(res=>{})
											uni.navigateBack()
										})
									})
								},
								fail: (e) => {
									console.log("图片转换失败");
								}
							})


							// let path = res.tempFilePath;
							// _this.handlePreviewImage(path);
							//上传资源到服务器

						},
						fail: (res) => {
							uni.showToast({
								title: '提交失败，请重新尝试',
								icon: 'none'
							});
						},
					});
				} catch (err) {
					uni.showToast({
						title: '签名失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			handlePreviewImage(imagePath) {
				const _this = this;
				const previewDom = uni.createSelectorQuery().in(_this).select('#previewCanvas');
				previewDom.fields({
					node: true,
					size: true
				}).exec((res) => {
					// Canvas 对象
					const canvas = res[0]?.node;
					// 渲染上下文
					const previewCtx = canvas.getContext('2d');
					const image = canvas.createImage();
					image.src = imagePath;
					image.onload = () => {
						let {
							width,
							height
						} = image;
						// 获取图片的宽高初始画布，canvas交换宽高
						canvas.width = height;
						canvas.height = width;
						// 设置白色背景
						previewCtx.fillStyle = '#FFFFFF';
						previewCtx.fillRect(0, 0, height, width);
						// 图片逆时针旋转90度，且换为弧度
						previewCtx.rotate((-90 * Math.PI) / 180);
						// 旋转后调整绘制的位置下移一个宽度的距离
						previewCtx.drawImage(image, -width, 0);
					};
					// 最终导出
					setTimeout(() => {
						uni.canvasToTempFilePath({
								canvas,
								fileType: 'png', // 指定文件类型
								quality: 1, // 最高质量
								success: (res) => {
									_this.previewImage = res.tempFilePath;
									uni.previewImage({
										urls: [res.tempFilePath],
										current: 0
									});
									_this.$emit('submit', res.tempFilePath);
								},
								fail: (err) => {
									uni.showToast({
										title: '合成失败，请重试',
										icon: 'none'
									});
								},
							},
							_this
						);
					}, 300); // 增加最终导出前的延迟
				});
			},
		},
	};
</script>
<style scoped>
	.wrapping {
		position: relative;
		padding: 20rpx;
		margin: 20rpx;
		background-color: #fff;
		box-sizing: border-box;
		padding-top: 100px;
	}

	.header-title {
		position: absolute;
		/* right: 20rpx; */
		top: 20rpx;
		height: 50rpx;
		z-index: 1000;
		transform-origin: top left;
		/* transform: translateX(100%) rotate(90deg); */
		font-size: 20rpx;
		color: #333;
	}

	.desc-text {
		color: #969799;
	}

	.small-preview {
		width: 100rpx;
		height: 50rpx;
		border-bottom: 1px solid #333;
	}

	.canvas-wrapper {
		position: relative;
		margin: auto;
		/* width: 60%;
		height: 80vh; */
		background: #f7f8fa;
		width: 100%;
		height: 60vh;
		padding-left: 80rpx;
		margin-top: -30px;
	}

	.char-group {
		position: absolute;
		top: 0px;
		left: 0px;
		width: 100%;
		height: 100%;
		pointer-events: none;
		user-select: none;
		z-index: 1;
		gap: 20rpx;
		display: flex;
		margin-left: 80rpx;
		margin-top: 20px;
	}

	.char-box {
		padding: 36rpx;
		/* width: 40vw;
		height: 50vw; */
		/* transform: rotate(90deg); */
		/* 	font-size: 30vw;
		line-height: 30vw; */
		text-align: center;
		color: #eeeeee;
		/* 使用虚线边框框住字体 */
		/* border: 1px dashed #ccc; */
		/* 使用米字格照片当背景图 */
		background: url('https://img1.baidu.com/it/u=2622499137,3527900847&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500') no-repeat;
		background-size: 100%;
		text-shadow: 1px 1px black, -1px -1px black, 1px -1px black, -1px 1px black;

		width: 22vw;
		height: 50vh;
		font-size: 15vw;
		line-height: 30vh;
	}

	.signature-canvas {
		position: relative;
		width: 100%;
		height: 100%;
		z-index: 2;
	}

	.footer-btn {
		position: absolute;
		/* left: 20rpx;
		bottom: 20rpx; */
		transform-origin: bottom right;
		/* transform: translateX(-100%) rotate(90deg); */
		z-index: 1000;
		gap: 32rpx;
		display: flex;

		right: 20rpx;
	}

	.action-btn {
		text-align: center;
		/* width: 200rpx;
		height: 96rpx; */
		border-radius: 100rpx;
		/* font-size: 32rpx;
		line-height: 96rpx; */
		color: #3874f6;
		border: 2rpx solid #3874f6;
		background: #fff;

		width: 200rpx;
		height: 40rpx;
		font-size: 18rpx;
		line-height: 40rpx;
	}

	.submit-btn {
		color: #fff;
		border: 2rpx solid #3874f6;
		background: #3874f6;
	}

	.preview-canvas {
		visibility: hidden;
		position: fixed;
		/* 将画布移出展示区域 */
		top: 100vh;
		left: 100vw;
		opacity: 0;
		z-index: 0;
	}
</style>